package p.ithorns.sample.office.example;

import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * MainController
 *
 * @author HtL
 * @date 2024/7/17 16:48
 * @since 1.0.0
 */
@RequestMapping("/word")
@RestController
public class WordController {

//    @ApiOperation(value = "下载")
    @PostMapping("/export")
    public void download(HttpServletResponse response) throws UnsupportedEncodingException {
        // response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8";
        try (
                OutputStream out = response.getOutputStream();
                XWPFDocument doc = getXWPFDocument();
        ) {
            response.setCharacterEncoding("utf8");
            response.setContentType(mediaType);//("application/force-download;charset=utf-8");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
            response.setHeader("Content-Disposition", "attachment; filename=" + encode("领导带班下井调班申请表.docx"));
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            doc.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 模拟获取数据
     */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private XWPFDocument getXWPFDocument() throws Exception {
        // BeanUtil.beanToMap(obj);
        Map<String, Object> valueMap = new HashMap<>();

        LocalDate date = LocalDate.now();
        valueMap.put("month", date.getMonthValue());
        valueMap.put("day", date.getDayOfMonth());

        ClassPathResource classPathResource = new ClassPathResource("/templates/word-tpl.docx");
        String resource = classPathResource.getURL().getPath();
        return WordExportUtil.exportWord07(resource, valueMap);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    private String encode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.name());
        return encode.replaceAll("\\+", "%20");
    }
}